var checkedCate = {};
var categories = {};
var markerClusterer, cateMarkers = {}, cateImages = {}, offsetx = {}, markersNum;
var oowin, clkWin;

function init(){
  checkedCate = {};
  categories = {};
  markerClusterer = null;
  cateMarkers = {};
  cateImages = {};
  offsetx = {};
  markersNum = 0;
  oowin = null;
  
  gaodeMap.init();
  rain.init();
  Scrollbar.init(document.querySelector('.foo--inside'));
  $(".clear-all").off().on("click", function(){
    init();
  });
  
  $("#menu_display").off().on("click", function(){
    $(".left-down").slideToggle();
  });
  $("#down-up").off().on("click", function(){
    $(".left-down").slideUp();
  });
  
  $(".floattool .layer_nav .icon").off().on("click", function(){
    $(".floattool .layer_nav .layer-pop").show(function(){
      $(".floattool .layer_nav .layer-pop .close").off().on("click", function(){
        $(".floattool .layer_nav .layer-pop").hide();
      });
      $(".floattool .layer_nav .layer-pop .layer-items a").off().on("click", function(){
        $(".floattool .layer_nav .layer-pop .layer-items a").removeClass("active");
        $(this).addClass("active");
        var name = $(this).attr("data-tag");
        switch(name){
        case 'dx':
          $(".check[data-tag='road']").removeClass("check").addClass("uncheck");
          var tags = [];
          $(".floattool .layer_nav .layer-pop .features .check").each(function(){
            tags.push($(this).attr("data-tag"));
          });
          gaodeMap.setDxLayer(tags);
          break;
        case 'normal':
          var tags = [];
          $(".floattool .layer_nav .layer-pop .features .check").each(function(){
            tags.push($(this).attr("data-tag"));
          });
          gaodeMap.setNormalLayer(tags);
          break;
        case 'satellite':
          $(".check[data-tag='road']").removeClass("check").addClass("uncheck");
          var tags = [];
          $(".floattool .layer_nav .layer-pop .features .check").each(function(){
            tags.push($(this).attr("data-tag"));
          });
          gaodeMap.setSatelliteLayer(tags);
          break;
        }
      });
      $(".floattool .layer_nav .layer-pop .layer-arguments .check, .floattool .layer_nav .layer-pop .layer-arguments .uncheck").off().on("click", function(){
        if($(this).hasClass("check")){
          $(this).removeClass("check");
          $(this).addClass("uncheck")
        }else{
          $(this).removeClass("uncheck");
          $(this).addClass("check")
        }
        var tag = $(this).attr("data-tag");
          if(tag != 'zoomMarker'){
          if(tag == 'cn'){
            gaodeMap.setShowLabel($(this).hasClass("check"));
          }else{
            var tags = [];
            $(".floattool .layer_nav .layer-pop .layer-arguments .check").each(function(){
              tags.push($(this).attr("data-tag"));
            });
            gaodeMap.setFeatures(tags);
          }
        }else{
          resetMarkers();
        }
      });
    });
  });
  
  //loadMenu();
  
  map.on("zoomend", function(){
    resetMarkers();
  });
}

function loadMenu(){
  ajax({
    basePath : serverUrl,
    url : '/api/war/category/list',
    data: {parentId: 0},
    success: function(cates){
      var h = '';
      cates.forEach(function(cate){
        h += '<li class="children children-lv1"><a class="lv1-title" href="javascript:void(0);" data-cateid="'+cate.cateId+'">'+cate.name+'<span class="triangle-down"></span></a></li>';
      })
      $(".classify-children").html(h);
      $("a.lv1-title").mouseover(function(){
        $(this).css('background','#eaf1fb');
      }).mouseout(function(){
        $(this).css('background','#ffffff');
      });
      $(".lv1-title").off().on("click", function(){
        if($(".triangle-down", $(this)).hasClass("rotate")){
          $(this).removeClass("chk1");
          $(".triangle-down", $(this)).removeClass("rotate");
          $("ul.ul-leaf", $(this).parents("li")).remove();
        }else{
          $(this).addClass("chk1");
          $(".triangle-down", $(this)).addClass("rotate");
          var cateId = $(this).attr("data-cateid");
          loadLv2($(this).parents("li"), cateId);
        }
        $("a.lv1-title").off("mouseover mouseout");
        $("a.lv1-title:not(.chk1)").mouseover(function(){
          $(this).css('background','#eaf1fb');
        }).mouseout(function(){
          $(this).css('background','#ffffff');
        });
      });
    }
  });
}

function loadLv2(parent, cateId){
  ajax({
    basePath : serverUrl,
    url : '/api/war/category/list',
    data: {parentId: cateId},
    success: function(cates){
      var html = '';
      cates.forEach(function(cate){
        html += '<li class="children children-lv2"><a class="lv2-title" href="javascript:void(0);" data-cateid="'+cate.cateId+'"><span class="checkbox" data-catetype="'+cate.type+'" data-cateid="'+cate.cateId+'" data-icon="'+(cate.icon?cate.icon:'')+'" data-over="'+(cate.overIcon?cate.overIcon:'')+'"></span><span class="lv2-text">'+cate.name+'</span><span class="help"></span></a><div class="lv2-info"></div></li>';
        categories[cate.cateId] = cate;
      });
      parent.append('<ul class="ul-leaf">' + html + '</ul>');
      $("ul.ul-leaf .checkbox", parent).off().on("click", function(){
        var cateId = $(this).attr("data-cateid");
        var catetype = $(this).attr("data-catetype");
        if($(this).hasClass("chk")){
          $(this).removeClass("chk");
          $(this).parents("li.children-lv2").removeClass("lv2-chk");
          $(".lv2-info", $(this).parents("li.children-lv2")).hide();
          checkedCate[cateId] = false;
          resetMarkers(cateId);
          resetImages(cateId);
        }else{
          checkedCate[cateId] = true;
          $(this).addClass("chk");
          $(this).parents("li.children-lv2").addClass("lv2-chk");
          //$(".lv2-info", $(this).parents("li.children-lv2")).html('<div class="marker-legend" style="background:#EE7600"></div>');
          var icon = $(this).attr("data-over");
          if(! icon){
            icon = $(this).attr("data-icon");
          }
          var t = '<div class="marker-legend" style="background:#EE7600"></div>';
          if(icon){
            t = '<div class="marker-legend"><img src="'+imageUrl+icon+'" height="16px"></div>';
          }
          if(catetype==1){
            $(".lv2-info", $(this).parents("li.children-lv2")).html(t);
            $(".lv2-info", $(this).parents("li.children-lv2")).show();
          }
          viewMarkers(cateId);
        }
      });
      for(var i in checkedCate){
        if(checkedCate[i]){
          var catetype = $("ul.ul-leaf .checkbox[data-cateid="+i+"]", parent).attr("data-catetype");
          $("ul.ul-leaf .checkbox[data-cateid="+i+"]", parent).addClass("chk");
          $("ul.ul-leaf .checkbox[data-cateid="+i+"]", parent).parents("li.children-lv2").addClass("lv2-chk");
          var icon = $(this).attr("data-over");
          if(! icon){
            icon = $(this).attr("data-icon");
          }
          var t = '<div class="marker-legend" style="background:#EE7600"></div>';
          if(icon){
            t = '<div class="marker-legend"><img src="'+imageUrl+icon+'" height="16px"></div>';
          }
          if(catetype==1){
            $(".lv2-info", $(this).parents("li.children-lv2")).html(t);
            $(".lv2-info", $(this).parents("li.children-lv2")).show();
          }
        }
      }
      $(".lv2-title").mouseover(function(e){
        var top = $(this).offset().top;
        var left = $(this).offset().left;
        var cateId = $(this).attr("data-cateid");
        var cate = categories[cateId];
        $("#winCard .tit").text(cate.name);
        $("#winCard .cnt").html(cate.desc ? cate.desc : "<无>");
        $("#winCard").css("top", top).show();
      }).mouseout(function(){
        $("#winCard").hide();
      });
    }
  });
}

var _renderClusterMarker = function (context) {
  var div = document.createElement('div');
  var bgColor = 'rgba(85,238,142,0.9)';
  var fontColor = 'rgba(0,0,0,1)';
  var borderColor = 'rgba(85,238,142,1)';
  var shadowColor = 'rgba(0,0,0,1)';
  div.style.backgroundColor = bgColor;
  var size = Math.round(10 + Math.pow(context.count / markersNum, 1 / 5) * 20);
  div.style.width = size * 1.5 + 'px';
  div.style.height = '24px';
  div.style.lineHeight = '24px';
  div.style.border = 'solid 1px ' + borderColor;
  //div.style.borderRadius = size / 2 + 'px';
  div.style.boxShadow = '0 0 1px ' + shadowColor;
  div.innerHTML = context.count;
  div.style.color = fontColor;
  div.style.fontSize = '14px';
  div.style.textAlign = 'center';
  context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
  context.marker.setContent(div)
};

function viewMarkers(cateId){
  var c = categories[cateId];
  if(c.type==3){
    $("#frameWin .common-panel-title").text(c.name);
    $("#frameWin .content-div").html(c.desc);
    var hei = $("#frameWin").height() - 25
    $("#frameWin .content-div").height(hei);
    if($(":hidden#frameWin").length==1){
      $("#frameWin").show();
      Scrollbar.init(document.querySelector('.foo--inside--dialog--frame'));
      showLoading();
    }
    $("#frameWin .close").off().on("click", function(){
      hideLoading();
      $("#frameWin").hide();
      $("span[data-cateid="+c.cateId+"]").removeClass("chk");
    });
    return ;
  }
  ajax({
    contentType: 'application/json',
    basePath : serverUrl,
    url : '/api/war/list',
    data : {"cateId" : cateId},
    success : function(data) {
      if(data && data.length > 0){
        var markers = [];
        var images = [];
        data.forEach(function(item){
          if(item.cateType == 1){
            var marker;
            var icon = item.overIcon ? item.overIcon : (item.icon ? item.icon : "");
            if(icon){
              if(! offsetx[cateId]){
                var img = new Image();
                img.src = imageUrl + icon;
                img.onload = function(){
                  offsetx[cateId] = img.width / 2;
                }
              }
              marker = new AMap.Marker({
                position: new AMap.LngLat(item.lng, item.lat),
                icon: imageUrl + icon,
                //icon: './ab_c.png',
                //offset: new AMap.Pixel(-15, -15)
              })
            }else{
              marker = new AMap.Marker({
                position: new AMap.LngLat(item.lng, item.lat),
                //offset: new AMap.Pixel(-15, -15)
              })
            }
            marker.content = item.id + "";
            marker.cateId = cateId;
            marker.zoom = item.zoom;
            marker.on('click', markerClick);
            marker.on('mouseover', markerMouseover);
            marker.on('mouseout', markerMouseout);
            markers.push(marker);
          }else{
            var pics = item.pictures;
            pics.forEach(function(pic){
              var imageLayer = new AMap.ImageLayer({
                url: imageUrl + pic.url,
                bounds: new AMap.Bounds(
                    [item.lng, item.lat],
                    [item.lng2, item.lat2]
                ),
                zIndex: 110,
                zooms: [3, 12]
              });
              images.push(imageLayer);
            });
          }
        });
        cateMarkers[cateId] = markers;
        cateImages[cateId] = images;
        resetMarkers();
        resetImages();
      }
    }
  })
}

function markerMouseout(e){
  if(oowin){
    oowin.close();
  }
}
function markerMouseover(e){
  if(clkWin && clkWin.getIsOpen()){
    if(clkWin.infoId == e.target.content){
      return;
    }
  }
  $.ajax({
    url: serverUrl + '/api/war/info',
    data: {'id': e.target.content},
    type: 'post',
    dataType: 'json',
    success: function(res){
      if (res.code == 0) {
        var cateId = e.target.cateId;
        var xx = offsetx[cateId];
        if(xx){
          xx = xx - 8;
        }else{
          xx = 0;
        }
        oowin = new AMap.InfoWindow({ anchor: 'top-left', autoMove: true, offset: new AMap.Pixel(xx, -10)});
        var data = res.data;
        var html = '<div class="main"><table class="tab">' + 
          '<tr><td>监测站：</td><td>'+(data.stationNames ? data.stationNames : '')+'</td></tr>' + 
          infos(data.infos) + '</table></div>';
        oowin.setContent('<div className="custom-infowindow input-card" class="foo--inside2" style="width:210px;height:190px">' + html + '</div>');
        oowin.open(map, e.target.getPosition());
        setTimeout(function(){
          Scrollbar.init(document.querySelector('.foo--inside2'));
        }, 100);
      } else {
        alert(res.msg)
      }
    }
  });
  function infos(infos){
    var idx = 0;
    var html = '';
    for(var key in infos){
      html += '<tr><td>'+key+'：</td><td>'+infos[key]+'</td></tr>';
      if(idx > 1){
        break;
      }
      idx ++;
    }
    return html;
  }
}
function markerClick(e){
  if(clkWin && clkWin.getIsOpen()){
    if(clkWin.infoId == e.target.content){
      return;
    }
  }
  $.ajax({
    url: serverUrl + '/api/war/info',
    data: {'id': e.target.content},
    type: 'post',
    dataType: 'json',
    success: function(res){
      if (res.code == 0) {
        var cateId = e.target.cateId;
        var xx = offsetx[cateId];
        if(xx){
          xx = xx - 8;
        }else{
          xx = 0;
        }
        clkWin = new AMap.InfoWindow({autoMove: true, offset: new AMap.Pixel(xx, -30)});
        var data = res.data;
        var html = '<div class="main"><table class="tab">' + picture(data.pictures) + '<tr><td>监测站：</td><td>'+(data.stationNames ? data.stationNames : '')+'</td></tr>';
        var num = 0;
        for(var key in data.infos){
          html += '<tr><td>'+key+'：</td><td>'+data.infos[key]+'</td></tr>';
          num ++;
        }
        html += '</table></div>';
        var h = (num + 2) * 38;
        if(h > 500) h = 500;
        clkWin.infoId = e.target.content;
        clkWin.setContent('<div className="custom-infowindow input-card" class="foo--inside1" style="width:515px;height:'+h+'px">' + html + '</div>');
        clkWin.on("open", function(){
          setTimeout(function(){
            Scrollbar.init(document.querySelector('.foo--inside1'));
            baguetteBox.run('.baguetteBoxOne');
          }, 60);
        });
        clkWin.open(map, e.target.getPosition());
      } else {
        alert(res.msg)
      }
    }
  });
  function infos(infos){
    var html = '';
    
    return html;
  }
  function picture(pics){
    var html = '';
    if(pics.length > 0){
      html = '<tr><td colspan="2"><div id="pictures" class="baguetteBoxOne gallery">';
      pics.forEach(function(pic){
        html += '<a href="'+imageUrl+pic.url+'" data-caption=""><img src="'+imageUrl+pic.url+'" height="70px"></a>';
      });
      html += '</div></td></tr>';
    }
    return html;
  }
}

function resetMarkers(cateId){
  //if(markerClusterer) markerClusterer.setMap(null);
  if(cateId){
    map.remove(cateMarkers[cateId] ? cateMarkers[cateId] : null);
    delete cateMarkers[cateId]; 
    return ;
  }
  map.clearInfoWindow();
  for(var o in cateMarkers){
    if(cateMarkers[o]){
      map.remove(cateMarkers[o]);
    }
  }
  var markers = [];
  for(var o in cateMarkers){
    if(cateMarkers[o]){
      if($(".floattool .layer_nav .layer-pop span[data-tag=zoomMarker]").hasClass("check")){
        var mapZoom = map.getZoom();
        cateMarkers[o].forEach(function(marker){
          if(mapZoom >= marker.zoom){
            markers.push(marker);
          }
        });
      }else{
        markers = markers.concat(cateMarkers[o]);
      }
    }
  }
  map.add(markers)
//  markersNum = markers.length;
//  markerClusterer= new AMap.MarkerClusterer(map, markers, {
//    maxZoom: 18,
//    gridSize: 80,
//    renderClusterMarker: _renderClusterMarker
//  });
}
function resetImages(cateId){
  if(cateId){
    var images = cateImages[cateId];
    map.remove(images);
    delete cateImages[cateId]; 
  }
  var images = [];
  for(var o in cateImages){
    images = images.concat(cateImages[o]);
  }
  map.add(images);
}

init();